<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input :placeholder="$t('table.name')" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
            <el-input :placeholder="$t('table.scode')" v-model="listQuery.scode" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
            <el-select v-model="listQuery.sale" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
                <el-option v-for="(item, index) in saleOptions" :key="index" :label="item.name" :value="item.value" />
            </el-select>
            <el-select v-model="listQuery.available" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
                <el-option v-for="(item, index) in availableOptions" :key="index" :label="item.name" :value="item.value" />
            </el-select>
            <el-cascader
              :placeholder="$t('placeholder.select')"
              v-model="listQuery.category_id"
              :options="categoryOptions"
              clearable
              change-on-select
               class="filter-item"
               style="width: 350px"
            ></el-cascader>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
        </div>
        <div>
            <el-table
            v-loading="listLoading"
            :key="tableKey"
            :data="groupLists"
            border
            fit
            highlight-current-row
            :default-sort = "{prop: 'id', order: 'descending'}"
            @sort-change="groupListSort"
            @selection-change="handleSelectionChange"
            style="width: 100%;">
            <el-table-column
                type="selection"
                width="35">
            </el-table-column>
            <el-table-column :label="$t('table.id')" align="center" width="65" sortable="custom" prop="id">
                <template slot-scope="scope">
                <span>{{ scope.row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.image')" min-width="120px">
                <template slot-scope="scope">
                <img class="plistImg" :src="scope.row.mphoto_url" >
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.name')" min-width="150px">
                <template slot-scope="scope">
                <span>{{ scope.row.curname }}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.scode')" min-width="150px">
                <template slot-scope="scope">
                <span>{{ scope.row.scode }}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.available')" class-name="status-col" width="100">
                <template slot-scope="scope">
                <el-tag :type="scope.row.is_available | availableFilter">{{ scope.row.available_name }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.sale')" class-name="status-col" width="100">
                <template slot-scope="scope">
                <el-tag :type="scope.row.is_sale | saleFilter">{{ scope.row.sale_name }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.created_at')" width="160px" align="center">
                <template slot-scope="scope">
                <span>{{ scope.row.created_at }}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.sort')" width="160px" align="center" sortable="custom" prop="sort">
                <template slot-scope="scope">
                <span><el-input v-model="scope.row.sort" type="number" min="0" @change="handelGroupSort(scope.row)" /></span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="handleUpdate(scope.$index)">{{ $t('table.edit') }}</el-button>
                <el-button size="mini" type="danger" @click="openDel(scope.row)">{{ $t('table.delete') }}
                </el-button>
                </template>
            </el-table-column>
            </el-table>

            <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        </div>
        <div>
            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="900px">
                <el-tabs v-model="editableTabsValue" type="card" @tab-click="handleClick">
                    <el-tab-pane
                        :label="$t('table.basicInfo')"
                        name="basicInfo"
                    >
                        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="160px" style="margin-left:30px;">
                        <el-form-item :label="$t('table.area')">
                            <el-select v-model="temp.area_id" 
                                style="width: 560px;"
                                multiple
                                filterable
                                allow-create
                                default-first-option
                                @change="handleLocationChange"
                                :placeholder="$t('placeholder.select')">
                                <el-option v-for="(item, index) in areaOptions" :key="index" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('table.location')">
                            <el-select
                            v-model="temp.location_id"
                            style="width: 450px;"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            :placeholder="$t('placeholder.select')">
                                <el-option-group
                                    v-for="area in locationOptions"
                                    :key="area.id"
                                    :label="area.name"
                                    :value="area.id">
                                    <el-option
                                    v-for="location in area.locations"
                                    :key="location.id"
                                    :label="location.name"
                                    :value="location.id">
                                    </el-option>
                                </el-option-group>
                            </el-select>
                            <el-checkbox v-model="is_location_all" @change="handleLocationAll">{{ $t('table_element.available.all') }}</el-checkbox>
                        </el-form-item>
                        <el-form-item :label="$t('table.available')">
                            <el-radio v-model="temp.is_available" label="1" name="is_avaliable">{{ $t('table_element.available.on') }}</el-radio>
                            <el-radio v-model="temp.is_available" label="0" name="is_avaliable">{{ $t('table_element.available.un') }}</el-radio>
                        </el-form-item>
                        <el-form-item :label="$t('table.sale')">
                            <el-radio v-model="temp.is_sale" label="1" name="is_sale">{{ $t('table_element.sale.on') }}</el-radio>
                            <el-radio v-model="temp.is_sale" label="0" name="is_sale">{{ $t('table_element.sale.un') }}</el-radio>
                        </el-form-item>
                        <el-form-item :label="$t('table.custom')">
                            <el-radio v-model="temp.is_custom" label="0" name="is_custom">{{ $t('table_element.custom.no') }}</el-radio>
                            <el-radio v-model="temp.is_custom" label="1" name="is_custom">{{ $t('table_element.custom.yes') }}</el-radio>
                        </el-form-item>
                        
                        <el-form-item :label="$t('table.pshortcode')">
                            <el-input style="width: 440px;" class="filter-item" v-model="temp.scode" name="productShortCode" /> 
                            <el-button style="margin-left: 10px;" type="primary"  @click="getShortCode">{{ $t('table.ax_match') }}</el-button>
                        </el-form-item>
                        <el-form-item :label="$t('table.category')">
                             <el-cascader 
                                :placeholder="$t('placeholder.select')"
                                v-model="temp.category_id" 
                                :options="categoryOptions"
                                change-on-select
                                style="width: 450px"
                                ></el-cascader>
                           <!--  <el-select v-model="temp.category_id" class="filter-item" :placeholder="$t('placeholder.select')">
                            <el-option v-for="(item, index) in categoryOptions" :key="index" :label="item.name" :value="item.id" />
                            </el-select> -->
                        </el-form-item>
                        <!-- <el-form-item :label="$t('table.ord_menu_cate')">
                            <el-select v-model="temp.omcategory" class="filter-item" :placeholder="$t('placeholder.select')">
                            <el-option v-for="(item, index) in ordMenuCateOptions" :key="index" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item> -->

                        <el-form-item  :label="$t('table.price')">
                            <el-row :gutter="10">
                            <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.qty') }}</div></el-col>
                            <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.price') }}</div></el-col>
                            <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.kcal') }}</div></el-col>
                            <el-col :span="4"><div class="grid-content bg-purple">{{ $t('table.capacity') }}</div></el-col>
                            <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.protein') }}</div></el-col>
                            <el-col :span="4"><div class="grid-content bg-purple">{{ $t('table.pcode') }}</div></el-col>
                            </el-row>
                            <el-row :gutter="10" v-for="(item, index) in temp.price" :key="index">
                            <el-col :span="3">
                                <div class="grid-content bg-purple">
                                <el-input v-model.number="item.qty" name="qty[]" />
                                </div>
                            </el-col>
                            <el-col :span="3">
                                <div class="grid-content bg-purple">
                                <el-input v-model="item.price" name="price[]" />
                                </div>
                            </el-col>
                            <el-col :span="3">
                                <div class="grid-content bg-purple">
                                <el-input v-model="item.kcal" name="kcal[]" />
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="grid-content bg-purple">
                                <el-input v-model="item.capacity" name="capacity[]" />
                                </div>
                            </el-col>
                            <el-col :span="3">
                                <div class="grid-content bg-purple">
                                <el-input v-model="item.protein" name="protein[]" />
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="grid-content bg-purple">
                                <el-input v-model="item.pcode" name="pcode[]" />
                                </div>
                            </el-col>
                            </el-row>

                            <el-row >
                            <el-button style="font-size:20px;" type="text" @click="addPrice()" class="el-icon-circle-plus-outline" ></el-button>
                            <el-button style="font-size:20px;" type="text" @click="delPrice()" class="el-icon-remove-outline" ></el-button>
                            </el-row>
                        </el-form-item>
                        
                        <el-form-item :label="$t('table.tags')">
                            <el-select
                            v-model="temp.tag_id"
                            style="width: 560px;"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            :placeholder="$t('placeholder.select')">
                            <el-option
                                v-for="item in tags"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('table.ingredients')">
                            <el-select
                            v-model="temp.ingredient_id"
                            style="width: 560px;"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            :placeholder="$t('placeholder.select')">
                            <el-option
                                v-for="item in ingredientOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item :label="$t('table.benefits')">
                            <el-select
                            v-model="temp.benefit_id"
                            style="width: 560px;"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            :placeholder="$t('placeholder.select')">
                            <el-option
                                v-for="item in benefitOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                            </el-select>
                        </el-form-item>

                        <!-- <el-form-item :label="$t('table.supplements')">
                            <el-select
                            v-model="temp.supplement_id"
                            style="width: 560px;"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            :placeholder="$t('placeholder.select')">
                            <el-option
                                v-for="item in supplementOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                            </el-select>
                        </el-form-item> -->

                        <el-form-item :label="$t('table.master_photo')">
                            <el-upload
                            class="upload-demo"
                            action=""
                            :show-file-list="false"
                            :auto-upload="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                            :on-change="changeFile">
                            <el-button size="small" type="primary">{{$t('table.browse')}}</el-button>
                            <img v-if="temp.mphoto" :src="temp.mphoto_url" class="avatar" >
                            </el-upload>
                        </el-form-item>

                        <el-form-item :label="$t('table.sort')">
                            <el-input v-model="temp.sort" name="sort" min="0" type="number" style="width: 100px" />
                        </el-form-item>

                        <template>
                            <el-tabs v-model="activeName" >
                            <el-tab-pane label="en" name="first">
                                <el-form-item :label="$t('table.name')" required>
                                <el-input v-model="temp.name" name="name" />
                                </el-form-item>
                                <el-form-item :label="$t('table.description')">
                                <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.description"></el-input>
                                </el-form-item>
                                <el-form-item :label="$t('table.content')">
                                <tinymce :height="300" id="fContent" v-model="temp.content"/>
                                </el-form-item>
                            </el-tab-pane>
                            <el-tab-pane label="zh-ch" name="second">
                                <el-form-item :label="$t('table.name')">
                                <el-input v-model="temp.cnname" name="cnname" />
                                </el-form-item>
                                <el-form-item :label="$t('table.description')">
                                <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.cndescription"></el-input>
                                </el-form-item>
                                <el-form-item :label="$t('table.content')">
                                <tinymce :height="300" id="fCNContent" v-model="temp.cncontent"/>
                                </el-form-item>
                            </el-tab-pane>
                            <el-tab-pane label="zh-hk" name="third">
                                <el-form-item :label="$t('table.name')">
                                <el-input v-model="temp.hkname" name="hkname" />
                                </el-form-item>
                                <el-form-item :label="$t('table.description')">
                                <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.hkdescription"></el-input>
                                </el-form-item>
                                <el-form-item :label="$t('table.content')">
                                <tinymce :height="300" id="fHKContent" v-model="temp.hkcontent"/>
                                </el-form-item>
                            </el-tab-pane>
                            <el-tab-pane label="zh-tw" name="fourth">
                                <el-form-item :label="$t('table.name')">
                                <el-input v-model="temp.twname" name="twname" />
                                </el-form-item>
                                <el-form-item :label="$t('table.description')">
                                <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.twdescription"></el-input>
                                </el-form-item>
                                <el-form-item :label="$t('table.content')">
                                <tinymce :height="300" id="fTWContent" v-model="temp.twcontent"/>
                                </el-form-item>
                            </el-tab-pane>
                            </el-tabs>
                        </template>

                        </el-form>
                    </el-tab-pane>
                    <!-- <el-tab-pane
                        :label="$t('table.nutrilonFacts')"
                        name="nutrilonFacts"
                    >
                        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="160px" style="margin-left:30px;">
                        
                        <el-form-item :label="$t('table.unit_for_per')">
                            <el-input v-model="temp.nutrition.per" name="per" style="width: 200px;"/>
                            <el-input v-model="temp.nutrition.unit" name="unit" style="width: 100px;"/>
                        </el-form-item>
                        <el-form-item :label="$t('table.energy')">
                            <el-input v-model="temp.nutrition.energy" name="energy" style="width: 300px;"/> Kcal
                        </el-form-item>
                        <el-form-item :label="$t('table.protein')">
                            <el-input v-model="temp.nutrition.nprotein" name="protein" style="width: 300px;" /> g
                        </el-form-item>
                        
                        <el-form-item :label="$t('table.total_fat')">
                            <el-input v-model="temp.nutrition.totalfat" name="total_fat" style="width: 300px;" /> g
                        </el-form-item>
                        
                        <el-form-item :label="$t('table.saturated_fat')">
                            <el-input v-model="temp.nutrition.saturatedfat" name="saturated_fat" style="width: 300px;" /> g
                        </el-form-item>
                        <el-form-item :label="$t('table.trans_fat')">
                            <el-input v-model="temp.nutrition.transfat" name="trans_fat" style="width: 300px;" /> g
                        </el-form-item>
                        <el-form-item :label="$t('table.cholesterol')">
                            <el-input v-model="temp.nutrition.cholesterol" name="cholesterol" style="width: 300px;" /> mg
                        </el-form-item>
                        <el-form-item :label="$t('table.total_carbohydrates')">
                            <el-input v-model="temp.nutrition.totalcarbohydrates" name="total_carbohydrates" style="width: 300px;" /> g
                        </el-form-item>
                        <el-form-item :label="$t('table.dietary_fibre')">
                            <el-input v-model="temp.nutrition.dietaryfibre" name="dietary_fibre" style="width: 300px;" /> g
                        </el-form-item>
                        <el-form-item :label="$t('table.sugars')">
                            <el-input v-model="temp.nutrition.sugars" name="sugars" style="width: 300px;" /> g
                        </el-form-item>
                        <el-form-item :label="$t('table.sodium')">
                            <el-input v-model="temp.nutrition.sodium" name="sodium" style="width: 300px;" /> mg
                        </el-form-item>
                        </el-form>
                    </el-tab-pane> -->
                    <el-tab-pane 
                        :label="$t('table.products')"
                        name="products"
                    >   
                        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="0" style="margin-left:30px;" class="group-product">
                            <el-form-item  label="">
                                <el-row :gutter="10">
                                    <el-col :span="3"><div class="grid-content bg-purple text-center">{{ $t('group_table.image') }}</div></el-col>
                                    <el-col :span="6"><div class="grid-content bg-purple">{{ $t('group_table.product_name') }}</div></el-col>
                                    <el-col :span="3"><div class="grid-content bg-purple">{{ $t('group_table.short_code') }}</div></el-col>
                                    <el-col :span="3"><div class="grid-content bg-purple">{{ $t('group_table.optional') }}</div></el-col>
                                    <el-col :span="4"><div class="grid-content bg-purple">{{ $t('group_table.default_qty') }}</div></el-col>
                                    <el-col :span="3"><div class="grid-content bg-purple">{{ $t('group_table.max_qty') }}</div></el-col>
                                    <el-col :span="2"><div class="grid-content bg-purple">{{ $t('group_table.operate') }}</div></el-col>
                                </el-row>
                                <product-items v-for="(item, index) in changeTemp.product" :product-list="productList" :item-obj="item" :is-custom="temp.is_custom"  :idx="index" :key="index" @change-product="changeProduct" @remove-product="removeProduct"></product-items>
                                <el-row >
                                    <el-button style="font-size:20px;" v-if="changeTemp.product.length <= 10 || temp.is_custom === '1'" type="text" @click="addProduct()" class="el-icon-circle-plus-outline" ></el-button>
                                </el-row>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
                    <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
                </div>
            </el-dialog>
            <el-dialog
                :visible.sync="delVisible"
                width="30%"
                >
                <span>{{$t('table.delInfo')}}</span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="delVisible = false">{{$t('table.cancel')}}</el-button>
                    <el-button type="danger" @click="deleteData">{{$t('table.delete')}}</el-button>
                </span>
            </el-dialog>
        </div>
        <!-- <div class="">
            <el-button type="primary" @click="onSubmit">{{ $t('table.confirm') }}</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        </div> -->
    </div>
</template>
<script>
import { fetchAll, fetchStore } from '@/api/product'
import { fetchAll as fetchGroupAll, fetchList as fetchGroupList, fetchStore as fetchGroupStore, fetchUpdate as fetchUpdateGroup, fetchDelete, fetchBatchDelete, fetchSort } from '@/api/group'
import { fetchAll as fetchLocation, fetchGroup as fetchLocationGroup } from '@/api/location'
import { fetchUpimg } from '@/api/upload'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination'
import Tinymce from '@/components/Tinymce'
import ProductItems from '@/components/GroupProduct/ProductItems'
import i18n from '@/lang/index'
export default {
    name: 'Group',
    components: { Pagination, Tinymce, ProductItems },
    directives: { waves },
    filters: {
        availableFilter(status) {
            const availableMap = [
                'danger',
                'success'
            ]
            return availableMap[status]
        },
        saleFilter(status) {
            const saleMap = [
                'danger',
                'success'
            ]
            return saleMap[status]
        }
    },
    data () {
        return {
            activeName: 'first',
            isAvailable: 2,
            is_location_all: 0,
            delVisible: false,
            cRow: {},
            isSale: 2,
            listLoading: false,
            tableKey: 0,
            total: 0,
            listQuery: {
                category_id: [],
                page: 1,
                limit: 20,
                available: 2,
                sale: 2,
                name: '',
                scode: '',
                order: 'id',
                sort: 'desc',
                lang: i18n.locale,
                area: this.$store.getters.area
            },
            group_ids: [],
            locationOptions: [],
            availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, {'value': 0, 'name': i18n.t('table_element.available.un') }],
            saleOptions: [{ 'value': 2, 'name': i18n.t('table_element.sale.all') }, { 'value': 1, 'name': i18n.t('table_element.sale.on') }, {'value': 0, 'name': i18n.t('table_element.sale.un') }],
            groups: [],
            tags: [],
            groupLists: [],
            quantOptions: [0, 1, 2, 3],
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: 'Edit',
                create: 'Create'
            },
            productList: [
                {
                    id: '',
                    name:'',
                    scode: '',
                    mphoto: '',
                    lang: ''
                }
            ],
            temp: {
                id: '',
                is_available: "1",
                is_sale: "1",
                is_custom: '0',
                sort: 0,
                name: '',
                cnname: '',
                hkname: '',
                twname: '',
                content: '',
                cncontent: '',
                hkcontent: '',
                twcontent: '',
                area_id: [96],
                location_id: [],
                price: [
                    {
                        qty: 0,
                        price: 0,
                        kcal: '',
                        capacity: '',
                        protein: '',
                        pcode: ''
                    }
                ],
                nutrition: {
                    per: 0,
                    unit: '',
                    energy: '',
                    nprotein: '',
                    totalfat: '',
                    saturatedfat: '',
                    transfat: '',
                    cholesterol: '',
                    totalcarbohydrates: '',
                    dietaryfibre: '',
                    sugars: '',
                    sodium: '',
                },
                tag_id: [],
                ingredient_id: [],
                // supplement_id: [],
                benefit_id: [],
                scode: '',
                mphoto: '',
                omcategory: 1,
                category_id: [],
                product: [{
                    product_name: '',
                    product_scode: '',
                    product_lang: '',
                    product_id: '',
                    product_mphoto: '',
                    product_mphoto_url: '',
                    qty: 1,
                    dqty: 1,
                    mqty: 1
                }]
            },
            rules: {
                name: [{ required: true, message: 'name is required', trigger: 'blur' }],
                mphoto: [{ required: true, message: 'main photo is required', trigger: 'blur' }]
            },
            editableTabsValue: 'basicInfo',
            changeTemp: {
                product: []
            }
        }
    },
    computed: {
        areaOptions: function () {
            return this.$store.state.locale.areas
        },
        // ordMenuCateOptions: function () {
        //     return this.$store.state.locale.productMmcAlls
        // },
        // tags: function () {
        //     return this.$store.state.locale.alltag
        // },
        categoryOptions: function () {
            return this.$store.state.locale.categoryTree
        },
        ingredientOptions: function () {
            return this.$store.state.locale.ingredients
        },
        benefitOptions: function () {
            return this.$store.state.locale.benefits
        },
        // supplementOptions: function () {
        //     return this.$store.state.locale.supplements
        // }
    },
    mounted () {
        var _this = this
        this.getList()
        this.getLocation()
        let par = {
            /* lang: i18n.locale,
            area: 96 */
            /* category_id: [
                _this.getDrinkId()
            ] */
            category_name: ['JUICES', 'SUPPLEMENT']
        }
        fetchAll(par).then(res => {
            var data = res.data
            if (data.data && data.data.length > 0) {
                _this.productList = data.data
            }
        })
        console.log('_this.productList', _this.productList)
        _this.listLoading = true
    },
    methods: {
        getDrinkId(){
            let list = this.$store.state.locale.categoryTree
            let id = 26
            if(list.length > 0){
                list.forEach(cat => {
                    if(cat.label.toUpperCase() === "DRINKS"){
                        cat.children.forEach(subsub => {
                            if(subsub.label.toUpperCase() === "JUICES"){
                                id = subsub.value
                            }
                        })
                    }
                })
            }
            return id
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                window.tinymce.get('fContent').setContent('')
                window.tinymce.get('fCNContent').setContent('')
                window.tinymce.get('fHKContent').setContent('')
                window.tinymce.get('fTWContent').setContent('')
            })
        },
        getLocation() {// 地址列表
            let params = {
                area: this.temp.area_id
            }
            fetchLocationGroup(params).then((res) => {
                this.locationOptions = res.data.data
            })
        },
        resetTemp() {
            this.temp = {
                id: undefined,
                is_available: '1',
                is_sale: '1',
                is_custom: '0',
                sort: 0,
                name: '',
                cnname: '',
                hkname: '',
                twname: '',
                content: '',
                cncontent: '',
                hkcontent: '',
                twcontent: '',
                area_id: [96],
                location_id: [],
                price: [
                    {
                        qty: 0,
                        price: 0,
                        kcal: '',
                        capacity: '',
                        protein: '',
                        pcode: ''
                    }
                ],
                nutrition: {
                    per: 0,
                    unit: '',
                    energy: '',
                    nprotein: '',
                    totalfat: '',
                    saturatedfat: '',
                    transfat: '',
                    cholesterol: '',
                    totalcarbohydrates: '',
                    dietaryfibre: '',
                    sugars: '',
                    sodium: '',
                },
                tag_id: [],
                ingredient_id: [],
                // supplement_id: [],
                benefit_id: [],
                scode: '',
                mphoto: '',
                omcategory: 1,
                category_id: [],
                product: [{
                    product_name: '',
                    product_scode: '',
                    product_lang: '',
                    product_id: '',
                    product_mphoto: '',
                    product_mphoto_url: '',
                    qty: 1,
                    mqty: 1,
                    dqty: 1
                }],
                mphoto_url: ''
            }
            this.changeTemp.product = []
        },
        getList() {
            this.listLoading = true
            fetchGroupList(this.listQuery).then(response => {
                var data = response.data
                this.groups = data.data.data
                this.groupLists = JSON.parse(JSON.stringify(this.groups))
                this.total = data.data.total

                // Just to simulate the time of the request
                setTimeout(() => {
                this.listLoading = false
                }, 1.5 * 1000)
            })
        },
        handleUpdate(idx) {
            this.temp = Object.assign({}, this.groups[idx]) // copy obj
            this.temp.is_available = this.temp.is_available.toString()
            this.temp.is_sale = this.temp.is_sale.toString()
            this.temp.is_custom = this.temp.is_custom.toString()
            this.temp.timestamp = new Date(this.temp.timestamp)
            this.changeTemp = JSON.parse(JSON.stringify(this.temp))
            /* this.temp.mphotos = []
            if (this.temp.mphoto) {
                let file = { name: 'mphoto', url: this.temp.mphoto }
                this.temp.mphotos.push(file)
            } */
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                // this.$refs['dataForm'].clearValidate()
                window.tinymce.get('fContent').setContent(this.temp.content)
                window.tinymce.get('fCNContent').setContent(this.temp.cncontent)
                window.tinymce.get('fHKContent').setContent(this.temp.hkcontent)
                window.tinymce.get('fTWContent').setContent(this.temp.twcontent)
            })
        },
        openDel(row){
            this.cRow = row
            this.delVisible = true
        },
        deleteData() {
            this.$confirm('Confirm deletion?', 'Message', {
                confirmButtonText: 'Confirm',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {
                let row = this.cRow
                this.delVisible = false
                fetchDelete(row.id).then(response => {
                    var data = response.data
                    if (data.code == 0) {
                        this.$notify({
                            title: 'Success',
                            message: 'Delete Success!',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    }
                    
                })
            }).catch(() => {
                this.$message({
                type: 'info',
                message: 'Cancel'
                })
            })
        },
        handleMulDelete() {
            this.$confirm('Confirm deletion?', 'Message', {
                confirmButtonText: 'Confirm',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {
                console.log(this.group_ids)
                fetchBatchDelete({ group_id: this.group_ids }).then(response => {
                    var data = response.data
                    if (data.code == 0) {
                    this.$notify({
                        title: 'Success',
                        message: 'Delete Success!',
                        type: 'success',
                        duration: 2000
                    })
                    this.getList()
                    }
                })
            }).catch(() => {
                this.$message({
                type: 'info',
                message: 'Cancel'
                })
            })
        },
        handleSelectionChange(val) {
            val.forEach(element => {
                if (this.group_ids.indexOf(element.id) == -1) {
                this.group_ids.push(element.id)
                }
            })
        },
        changeProduct(data, index) {
            // this.changeTemp = JSON.parse(JSON.stringify(this.temp))
            this.changeTemp.product[index] = data
        },
        addPrice() {
            const item = {
                qty: 0,
                price: 0,
                kcal: '',
                capacity: '',
                protein: '',
                pcode: ''
            }
            this.temp.price.push(item)
        },
        delPrice() {
            let len = this.temp.price.length
            if (len > 0) {
                this.temp.price.splice(len-1)
            }
        },
        addProduct() {
            if(this.changeTemp.product.length < 10 || this.temp.is_custom === '1'){
                let item = {
                    product_name: '',
                    product_scode: '',
                    product_lang: '',
                    product_id: '',
                    product_mphoto: '',
                    product_mphoto_url: '',
                    qty: 1,
                    mqty: 1,
                    dqty: 1
                }
                this.changeTemp.product.push(item)
            } else {
                this.$message({
                    message: 'Maximum addable 10 products',
                    type: 'warning'
                })
            }
        },
        removeProduct(index) {
            // var index = this.groupProducts.indexOf(item)
            // if (index > 0) {
                this.changeTemp.product.splice(index, 1)
            // }
        },
        resetForm() {
            this.changeTemp = JSON.parse(JSON.stringify(this.temp))
            // this.$refs[formName].resetFields()
        },
        onSubmit() {
            /* let products = JSON.parse(JSON.stringify(this.groupProducts))
            let isValid = false
            for (let i in products) {
                if (!products[i].name) {
                    isValid = true
                    products.splice(i, 1)
                }
            }
            if (products.length > 0) {
                console.log(products)
                alert('submit!')
            } */
        },
        handleAvatarSuccess(res, file) {
            this.temp.mphoto = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        changeFile(file, fileList) {
            var This = this;
            // console.log(file)
            //this.imageUrl = URL.createObjectURL(file.raw);
            var reader = new FileReader();
            reader.readAsDataURL(file.raw);
            reader.onload = function(e){ 
                // this.result // 这个就是base64编码了
                This.imageUrl = this.result
                fetchUpimg({img: this.result}).then((res) => {
                    if (res.data && res.data.data && res.data.data.paths && res.data.data.paths.length > 0) {
                        This.temp.mphoto =  res.data.data.paths[0].path // res.data.data.imageDomain + '/' +
                        This.temp.mphoto_url = (res.data.data.paths[0].path.indexOf('http')==0) ? res.data.data.paths[0].path : res.data.data.imageDomain + '/' + res.data.data.paths[0].path
                    }
                })
            }
        },
        getShortCode() {
            // 获取shortCode
            // console.log(this.temp.productShortCode)
        },
        handleClick(tab, event) {
            // console.log(tab, event);
        },
        createData() {
            let This = this
            This.temp.product = JSON.parse(JSON.stringify(this.changeTemp.product))
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
                // this.temp.author = 'vue-element-admin'
                // this.temp.mphoto = this.temp.mphotos[0]
                This.temp.lang = i18n.locale
                fetchGroupStore(This.temp).then(() => {
                    This.groupLists.unshift(This.temp)
                    This.dialogFormVisible = false
                    This.$notify({
                        title: 'Success',
                        message: 'Create Success!',
                        type: 'success',
                        duration: 2000
                    })
                    This.getList()
                })
                }
            })
        },
        updateData() {
            let This = this
            This.temp.product = JSON.parse(JSON.stringify(this.changeTemp.product))
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                This.temp.lang = i18n.locale
                const tempData = Object.assign({}, This.temp)
                tempData.timestamp = + new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
                fetchUpdateGroup(This.temp.id, tempData).then(() => {
                    for (const v of This.groupLists) {
                    if (v.id === This.temp.id) {
                        const index = This.groupLists.indexOf(v)
                        This.groupLists.splice(index, 1, This.temp)
                        break
                    }
                    }
                    This.dialogFormVisible = false
                    This.$notify({
                        title: 'Success',
                        message: 'Update Success!',
                        type: 'success',
                        duration: 2000
                    })
                    this.getList()
                })
                }
            })
        },
        handelGroupSort(row) {
            fetchSort(row.id, event.target.value).then((res) => {
                if (res.data.code == 0) {
                this.$notify({
                    title: 'Success',
                    message: 'Update Success!',
                    type: 'success',
                    duration: 2000
                })
                }
            })
        },
        groupListSort(params) {
            // console.log(params.order)
            this.listQuery.order = params.prop
            this.listQuery.sort = params.order == 'ascending' ? 'asc' : 'desc'
            this.getList()
        },
        handleLocationChange() {
            this.getLocation();
        },
        handleLocationAll() {
            let area, location;
            this.temp.location_id = [];
            if (this.is_location_all) {
                for(area in this.locationOptions) {
                    for(location in this.locationOptions[area].locations) {
                        this.temp.location_id.push(this.locationOptions[area].locations[location].id);
                    }
                }
            }
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.group-product{
    .grid-content{
        display: block;
    }
    
}
.plistImg{
    max-width: 120px;
    max-height: 120px;
}
.el-upload{
    .avatar{
        // height: 40px;
        float: right;
        border: 1px solid #eee;
        margin-left: 10px;
    }
}
.groupItemWrap{
    padding: 15px 0px 0px 0px;
    border-top: 1px solid #f1f1f1;
}
</style>
